﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using Newtonsoft.Json;
using LiteDb;
using Newtonsoft.Json.Linq;
using System.Threading;

namespace DidaManager.Native.SerialPort
{
    public class SerialPortManager
    {
        private readonly SerialPortConfig _serialPortConfig;
        private readonly System.IO.Ports.SerialPort _serialPort;
        private Ymodem _ymodem;

        public SerialPortManager()
        {
            _serialPortConfig = new SerialPortConfig();
            _serialPort = new System.IO.Ports.SerialPort();
            _ymodem = new Ymodem();
        }

        public string GetSerialPort(string portName)
        {
            return _serialPortConfig.GetSerialPortValue(portName);
        }

        public object GetSerialPortList(object param)
        {
            var serialPortList = _serialPortConfig.m_dictSerialNames;
            // 需要把serialPortList转换为List<object>
            var list = new List<object>();
            foreach (var item in serialPortList)
            {
                list.Add(item.Key);
            }
            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list);
            return LiteDb.ApiResponse.Success(jsonString);
        }

        public Ymodem GetYmodem()
        {
            return _ymodem;
        }

        public bool IsSerialPortOpen()
        {
            if (_serialPort == null)
            {
                return false;
            }
            return _serialPort.IsOpen;
        }

        public object OpenSerialPort(object param)
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Close();
                    return ApiResponse.Fail("串口已打开");
                }
                var serialPortName = param.ToString();
                if (string.IsNullOrEmpty(serialPortName))
                {
                    return ApiResponse.Fail("串口名称不能为空");
                }
                // 获取端口号和波特率
                var jObject = JObject.Parse(serialPortName.ToString());
                if (jObject == null)
                {
                    return ApiResponse.Fail("参数错误");
                }
                var port = jObject["port"]?.ToString();
                var baudRate = jObject["baudRate"]?.ToString();
                if (string.IsNullOrEmpty(port) || string.IsNullOrEmpty(baudRate))
                {
                    return ApiResponse.Fail("端口号或波特率不能为空");
                }
                var portValue = _serialPortConfig.GetSerialPortValue(port);
                if (string.IsNullOrEmpty(portValue))
                {
                    return ApiResponse.Fail("端口号不存在");
                }

                _serialPort.DataReceived += _ymodem.SerialPort_DataReceived;

                // 设置结束符
                _serialPort.NewLine = "\r\n";
                _serialPort.ReadTimeout = 5000;// 设置读取超时时间，单位为毫秒
                _serialPort.PortName = portValue;
                _serialPort.BaudRate = int.Parse(baudRate);
                // 确保串口参数正确配置
                _serialPort.DataBits = 8;
                _serialPort.StopBits = System.IO.Ports.StopBits.One;
                _serialPort.Parity = System.IO.Ports.Parity.None;
                _serialPort.Open();
                _ymodem.SetSerialPort(_serialPort);
                return ApiResponse.Success("串口打开成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message);
            }
        }

        public object CloseSerialPort(object param)
        {
            try
            {
                if (!_serialPort.IsOpen)
                {
                    return ApiResponse.Fail("串口未打开");
                }
                _serialPort.Close();
                return ApiResponse.Success("串口关闭成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message);
            }
        }

        public object DownloadConfigViaSerial(object param)
        {
            try
            {
                if (!_serialPort.IsOpen)
                {
                    return ApiResponse.Fail("串口未打开");
                }
                return ApiResponse.Success("串口下载配置成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message);
            }
        }
    }
}
